package com.frxuexi.lib_base.base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception
import java.text.SimpleDateFormat

open class BaseViewModel:ViewModel() {

    fun <T> httpRequest(s:suspend ()->Res<T>,success:(T)->Unit){
        try {
            viewModelScope.launch {
                val res = s.invoke()
                if(res.code==200){

                    success(res.data)
                }else{
                    Log.i("===",res.message)
                }
            }
        }catch (e:Exception){
            Log.i("===",e.message.toString())
        }
    }

    fun <T> roomRequest(s:()->T,success:(T)->Unit){
        try {
            viewModelScope.launch {
                val res = s.invoke()
                if(res!=null){
                    success(res)
                }else{
                    Log.i("===","操作不正确")
                }
            }
        }catch (e:Exception){
            Log.i("===",e.message.toString())
        }
    }

    fun toBody(any: Any):RequestBody{
        return RequestBody.create("application/json".toMediaTypeOrNull(),Gson().toJson(any))
    }

    fun getDateTimeString(time:Long):String{
        return SimpleDateFormat("yyyyMMddHHmmss").format(time)
    }

    fun getDateTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }

    fun getDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getMonth():String{
        return SimpleDateFormat("MM").format(System.currentTimeMillis())
    }

    fun getYear():String{
        return SimpleDateFormat("yyyy").format(System.currentTimeMillis())
    }
}